import json

import MySQLdb
from django.db.models import Max
from django.http import JsonResponse
from django.views.generic import View
from app.libs.base_render import render_to_response
from app.model.auth import ClientUser, Collect
from django.core.paginator import Paginator
import pandas as pd
from app.model.video import Ratings, Video

# 获取视频信息
class Videos(View):

    TEMPLATE = 'client/video/video.html'

    def get(self, request):
        username = request.session['username']
        genres = request.GET.get('genres', 'null')
        searchfor = request.GET.get('searchfor', 'null')
        if searchfor != 'null':
            videos = Video.objects.filter(title__icontains=searchfor)
        elif genres != 'null':
            videos = Video.objects.filter(genres__icontains=genres)
        else:
            videos = Video.objects.all()
        page = request.GET.get('page', 1)
        pt = request.GET.get('pt', 'null')

        if pt != 'null':
            page = int(pt)
        p = Paginator(videos, 12)
        total_page = p.num_pages

        if int(page) <= 1:
            page = 1
        current_page = p.get_page(int(page)).object_list

        data = {'videos': current_page, 'total': total_page, 'page_num': int(page), 'username': username,
                'genres': genres, 'searchfor': searchfor}
        return render_to_response(request, self.TEMPLATE, data=data)


class Score(View):
    TEMPLATE = 'client/video/video.html'

    def post(self, request):
        score = request.POST.get('score', '')
        movieid = request.POST.get('movieid', '')
        # print(score, movieid)
        if ClientUser.objects.get(username=request.session['username']).userId == '':
            userid = int(Ratings.objects.latest('userId').userId) + 1
            ClientUser.objects.filter(username=request.session['username']).update(userId=userid)
            Ratings.add(userId=userid, movieId=movieid, rating=score)
        else:
            userid = ClientUser.objects.get(username=request.session['username']).userId
            print('123123123')
            if Ratings.objects.filter(userId=userid, movieId=movieid).exists():
                Ratings.objects.filter(userId=userid, movieId=movieid).update(rating=score)
                data = {'msg': '修改评分成功'}
                return JsonResponse(data)
            else:
                Ratings.add(userId=userid, movieId=movieid, rating=score)
        data = {'msg': '评分成功'}
        return JsonResponse(data)


class CollectFun(View):
    TEMPLATE = 'client/video/video.html'

    def post(self, request):
        movieid = request.POST.get('movieid', '')
        username = request.session['username']
        user = ClientUser.objects.filter(username=username).first()
        flag = Collect.objects.filter(username=user, movieId=int(movieid)).exists()
        if not flag:
            Collect.add(username=user, movieId=int(movieid))
            data = {'msg': '收藏成功'}
        else:
            data = {'msg': '您已收藏'}
        return JsonResponse(data)


class AddMovie(View):
    TEMPLATE = 'dashboard/auth/add_movie.html'

    def get(self, request):
        return render_to_response(request, self.TEMPLATE)

    def post(self, request):
        title = request.POST.get('title', '')
        genres = request.POST.getlist('genres_list', '')

        if not all([title, genres]):
            data = {'msg': '不能为空'}
            return JsonResponse(data)

        temp = ''
        for i in range(len(genres)):
            temp += genres[i] + '|'
        temp = temp[:-1]

        print('------------')
        print(title)
        print(type(title))

        movieId = Video.objects.all().aggregate(Max('movieId'))
        movieId = movieId['movieId__max'] + 1
        Video.objects.create(movieId=movieId, title=title, genres=temp)

        data = {'msg': '添加成功'}
        return JsonResponse(data)


class CF(View):
    TEMPLATE = 'client/video/CF.html'

    def get(self, request):
        username = request.session['username']
        data = {'username': username}

        mysql_cn = MySQLdb.connect(host='localhost', port=3306, user='root', passwd='root', db='haha', charset='utf8')
        df = pd.read_sql('select userId,movieId,rating from app_ratings', mysql_cn)
        df = df.pivot(index='userId', columns='movieId', values='rating')

        def build(user1_id, user2_id):
            flag = df.loc[user1_id].notnull() & df.loc[user2_id].notnull()
            return df.loc[user1_id, flag], df.loc[user2_id, flag]

        def pearson(user1_id, user2_id):
            x, y = build(user1_id, user2_id)
            mean1, mean2 = x.mean(), y.mean()
            # 分母
            denominator = (sum((x - mean1) ** 2) * sum((y - mean2) ** 2)) ** 0.5
            try:
                value = sum((x - mean1) * (y - mean2)) / denominator
            except ZeroDivisionError:
                value = 0
            return value

        # 计算最相似的邻居
        def Neighbor(user_id, m=3):
            return df.drop(user_id).index.to_series().apply(pearson, args=(user_id,)).nlargest(m)

        def recommend(user_id):
            # 找到最相似用户的id
            nearest_user_id = Neighbor(user_id).index[0]
            return nearest_user_id, df.loc[
                nearest_user_id, df.loc[user_id].isnull() & df.loc[nearest_user_id].notnull()].sort_values(
                ascending=False)

        userid = ClientUser.objects.filter(username=username).first().userId

        if not userid:
            data['msg'] = '请您先评价电影'
            return render_to_response(request, self.TEMPLATE, data=data)
        # print(userid)
        uid, mlist = recommend(int(userid))
        data['id'] = uid
        data['list'] = mlist.head(5)
        data['video'] = Video

        mysql_cn.close()
        return render_to_response(request, self.TEMPLATE, data=data)


class ShowRatedMovies(View):
    TEMPLATE = 'client/auth/showratedmovies.html'

    def get(self, request):
        username = request.session['username']
        flag = ClientUser.objects.get(username=username).userId
        print(flag)
        print(type(flag))
        if not flag:
            return render_to_response(request, self.TEMPLATE)
        else:
            userid = ClientUser.objects.get(username=username).userId
            rating = Ratings.objects.filter(userId=userid)
            result = []
            for a in rating:
                m = Video.objects.get(movieId=a.movieId)
                result.append(m)

            data = {'rating': rating, 'result': result}
            return render_to_response(request, self.TEMPLATE, data)
